<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
        {{ t('purchase.batch_entry') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form
      class="flex flex-wrap"
      :model="state.form"
      ref="formRef"
      :rules="rules as FormRules"
      label-width="22%"
    >
      <el-form-item :label="t('purchase.sup')" class="w-50%">
        <el-input v-model="state.row.supid_value" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.purchase_no')" class="w-50%">
        <el-input v-model="state.row.purchase_no" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.sales_orderno')" class="w-50%">
        <el-input v-model="state.row.sales_orderno" disabled />
      </el-form-item>
      <el-form-item :label="t('purchase.signatory')" class="w-50%">
        <el-input v-model="state.row.signatoryid_value" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.pay_type')" class="w-50%">
        <el-input v-model="state.row.pay_type_value" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.pay_terms')" class="w-50%">
        <el-input v-model="state.row.pay_terms_value" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.advance_delivery_date')" class="w-50%">
        <el-input v-model="state.row.advance_delivery_date" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.delivery_date')" class="w-50%">
        <el-date-picker
          :disabled="state.futures == 0"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled-date="disablePastDates"
          v-model="state.form.delivery_date"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item :label="t('purchase.warehouse')" class="w-50%" prop="warehouse">
        <el-tree-select
          v-model="state.form.warehouse"
          placeholder="请选择仓库"
          :data="state.warehouseList"
          filterable
          :multiple="state.futures === 2"
          @change="(val) => getSellableList(1, val)"
        />
      </el-form-item>

      <el-form-item :label="t('purchase.ccname_ids')" class="w-50%" prop="ccname_ids" required>
        <el-select
          v-model="state.form.ccname_ids"
          filterable
          multiple
          :placeholder="'请选择' + t('purchase.ccname_ids')"
        >
          <el-option label="全球" :value="0" />
          <el-option
            v-for="item in state.sellableList"
            :selected="item.is_sellable"
            :key="item.id"
            :label="item.cc_name"
            :value="item.id"
            :disabled="state.form.ccname_ids.includes(0)"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('purchase.arrival_batch')" class="w-50%" prop="arrival_batch">
        <el-input
          v-model="state.form.arrival_batch"
          :placeholder="'请输入' + t('purchase.arrival_batch')"
        />
      </el-form-item>

      <el-form-item :label="t('purchase.entry_type')" class="w-50%">
        <el-input v-model="state.entry_type" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.total_amount')" class="w-50%">
        <el-input v-model="state.row.total_amount" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.other_amount')" class="w-50%">
        <el-input v-model="state.row.other_amount" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.pay_amount')" class="w-50%">
        <el-input v-model="state.row.pay_amount" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.notes')" class="w-50%">
        <el-input v-model="state.row.notes" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.owner')" class="w-50%">
        <el-input v-model="state.row.owner_value" disabled />
      </el-form-item>

      <el-form-item :label="t('purchase.partner')" class="w-50%">
        <el-input v-model="state.row.partner_value" disabled />
      </el-form-item>
    </el-form>
    <el-divider content-position="left">采购明细-分批入库</el-divider>
    <el-table
      :key="currentKey"
      v-if="state.row.purchase_goods"
      :data="state.row.purchase_goods"
      border
      show-summary
      :summary-method="getSummaries"
      style="width: 100%; margin-top: 10px"
      :row-class-name="rowClassName"
      @cell-click="editCell"
    >
      <el-table-column prop="cname" label="产品名称">
        <template #default="{ row }">
          <span>{{ row.cname }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="产品编号">
        <template #default="{ row }">
          <span>{{ row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="order_no" label="订单编码">
        <template #default="{ row }">
          <span>{{ row.order_no }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="num" label="采购数量" width="150">
        <template #default="{ row }">
          <span>{{ row.num }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="entered_num" label="已入库数量" width="150">
        <template #default="{ row }">
          <span>{{ row.entered_num }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="entry_num" label="入库数量" width="200">
        <template #default="{ row }">
          <ElInputNumber
            v-model="row.entry_num"
            :min="0"
            :max="row.num - row.entered_num"
            type="number"
          />
        </template>
      </el-table-column>
      <el-table-column prop="warehouse" label="入库仓库">
        <template #default="{ row, $index }">
          <el-tree-select
            v-model="row.warehouse"
            placeholder="请选择仓库"
            :data="state.warehouseList"
            filterable
            :multiple="state.futures == 2"
            check-strictly
            :render-after-expand="false"
            style="width: 240px"
            @change="(val) => getSellableList(2, val, row, $index)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="warehouse" :label="t('purchase.ccname_ids')" min-width="180">
        <template #default="{ row, $index }">
          <el-select
            v-model="row.ccname_ids"
            filterable
            multiple
            :placeholder="'请选择' + t('purchase.ccname_ids')"
          >
            <el-option label="全球" :value="0" />
            <el-option
              v-for="item in state.sellableLists[$index] || []"
              :selected="item.is_sellable"
              :key="item.id"
              :label="item.cc_name"
              :value="item.id"
              :disabled="row.ccname_ids?.includes(0)"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="arrival_batch" label="物流批次">
        <template #default="{ row }">
          <!-- <el-form :model="row" :rules="rules" :hide-required-asterisk="true"> -->
          <!-- <el-form-item label="" prop="arrival_batch"> -->
          <el-input v-model="row.arrival_batch" placeholder="请输入最少6位批次码" />
          <!-- </el-form-item> -->
          <!-- </el-form> -->
        </template>
      </el-table-column>
      <el-table-column v-if="state.futures != 0" prop="delivery_date" label="到货日期">
        <template #default="{ row }">
          <el-date-picker
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disablePastDates"
            v-model="row.delivery_date"
          />
        </template>
      </el-table-column>
      <el-table-column prop="unit_price" label="采购单价" width="150">
        <template #default="{ row }">
          <el-input disabled v-model="row.unit_price" />
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="100">
        <template #default="scope">
          <ElButton
            class="input-button"
            size="small"
            type="primary"
            plain
            link
            @click.prevent="entryRow(scope.row, scope.$index)"
          >
            入库
          </ElButton>
        </template>
      </el-table-column>
    </el-table>
  </ContentDetailWrap>
</template>
<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import {
  ElMessage,
  TableColumnCtx,
  type FormRules,
  type FormInstance,
  ElMessageBox,
  ElLoading
} from 'element-plus'
import { getSecondWarehouseListApi, getfirstWarehouseListApi } from '@/api/warehouse/index'
import { getSellableListApi } from '@/api/regionCountry/index'
import { entryApi, batchEntryApi, getInfoApi } from '@/api/purchase'
import { useRouter, useRoute } from 'vue-router'
import { filterEmptyParams } from '@/utils'
import { isEqual } from 'lodash-es'
import { ref, reactive, watch, onMounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'

// 类型定义
interface PurchaseGood {
  id: number
  cname: string
  code: string
  style_code: string
  unit: string
  num: number
  unit_price: number
  unit_sum: number
  notes: string
  entered_num: number
  entry_num: number
  warehouse: number | number[] | null
  ccname_ids: number[] | null
  detail_id?: number
  arrival_batch?: string
  delivery_date?: string
  editing?: boolean
}

interface State {
  source: string
  futures: number
  entry_type: string
  row: Record<string, any>
  form: {
    id: number
    warehouse: number | number[] | null
    ccname_ids: number[]
    arrival_batch: string
    delivery_date: string
    futures: number
  }
  warehouseList: Record<string, any>[]
  sellableList: Record<string, any>[]
  sellableLists: Record<number, any[]>
}

interface SummaryMethodProps {
  columns: TableColumnCtx<PurchaseGood>[]
  data: PurchaseGood[]
}

// 常量定义
const FUTURES_TYPES = {
  SPOT: 0,
  IN_TRANSIT: 1,
  LARGE: 2
}

const { t } = useI18n()
const { push, go } = useRouter()
const route = useRoute()

// 工具函数
const getEntryType = (futures: number): string => {
  const types = {
    [FUTURES_TYPES.SPOT]: '现货',
    [FUTURES_TYPES.IN_TRANSIT]: '在途期货',
    [FUTURES_TYPES.LARGE]: '大期货'
  }
  return types[futures] || '未知类型'
}

// 响应式状态
const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()

const state = reactive<State>({
  source: route.query.source ? decodeURIComponent(route.query.source as string) : '',
  futures: Number(route.query.futures),
  entry_type: getEntryType(Number(route.query.futures)),
  row: {},
  form: {
    id: route.query.id ? Number(route.query.id) : 0,
    warehouse: Number(route.query.futures) === FUTURES_TYPES.LARGE ? [] : null,
    ccname_ids: [],
    arrival_batch: '',
    delivery_date: '',
    futures: Number(route.query.futures)
  },
  warehouseList: [],
  sellableList: [],
  sellableLists: {}
})

const disablePastDates = (time: Date): boolean => {
  return time.getTime() < Date.now()
}

const rowClassName = ({ row }: { row: PurchaseGood }): string => {
  return row.editing ? 'editing-row' : ''
}

const editCell = (row: PurchaseGood): void => {
  row.editing = true
}

// 表单验证规则
const rules = ref<FormRules>({
  warehouse: [
    {
      required: true,
      message: '请选择仓库',
      trigger: 'change'
    }
  ],
  ccname_ids: [
    {
      required: true,
      message: '请选择产品',
      trigger: 'change'
    }
  ],
  arrival_batch: [
    {
      required: true,
      message: '请输入最少6位批次码',
      trigger: 'blur'
    },
    {
      min: 6,
      message: '批次码长度不能少于6位',
      trigger: 'blur'
    }
  ]
})

// API 调用函数
const getWarehouseList = async (): Promise<void> => {
  const api =
    state.futures === FUTURES_TYPES.LARGE ? getfirstWarehouseListApi : getSecondWarehouseListApi

  const res = await api({})
  if (res?.data?.list) {
    state.warehouseList = res.data.list
  }
}

const getSellableList = async (
  type: number,
  val: number | number[],
  row?: PurchaseGood,
  index?: number
): Promise<void> => {
  const target = type === 1 ? state.form : row
  if (!target) return

  const resetCcnameIds = () => {
    target.ccname_ids = []
    if (type === 2 && index !== undefined) {
      state.sellableLists[index] = []
    }
  }

  if (!val || (Array.isArray(val) && val.length === 0)) {
    resetCcnameIds()
    return
  }

  const id = Array.isArray(val) ? val.join(',') : val
  if (!id) {
    resetCcnameIds()
    return
  }

  const resp = await getSellableListApi({ id })
  if (!resp?.data?.list) {
    resetCcnameIds()
    return
  }

  if (type === 1) {
    state.sellableList = resp.data.list
    target.ccname_ids = state.sellableList.filter((item) => item.is_sellable).map((item) => item.id)
  } else if (index !== undefined) {
    state.sellableLists[index] = resp.data.list
    target.ccname_ids = resp.data.list.filter((item) => item.is_sellable).map((item) => item.id)
  }
}

const getDet = async (): Promise<void> => {
  const resp = await getInfoApi(route.query.id as string)
  state.row = resp.data
  if (state.row.purchase_goods) {
    state.row.purchase_goods.forEach((row) => {
      row.ccname_ids = []
    })
  }
}

// 初始化函数
const currentKey = ref<string>('1')
const initialization = async (): Promise<void> => {
  await Promise.all([getWarehouseList(), getDet()])
  currentKey.value = Date.now().toString()
}

// 提交和入库相关函数
const submit = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) return

  if (state.futures !== FUTURES_TYPES.SPOT && !state.form.delivery_date) {
    ElMessage.error('期货到货日期不能为空')
    return
  }

  await formEl.validate(async (valid) => {
    if (!valid) return

    try {
      await ElMessageBox.confirm('是否确认全部入库?', t('confirmMessage.warning'), {
        confirmButtonText: t('confirmMessage.ok'),
        cancelButtonText: t('confirmMessage.cancel'),
        type: 'warning'
      })

      const params = filterEmptyParams({ ...state.form })
      const resp = await batchEntryApi(params)
      if (resp.code === 0) {
        ElMessage.success(t('common.operateSucMsg'))
        push('/purchase/purchase-order-management')
      }
    } catch (error) {
      // 用户取消操作
    }
  })
}

const entryRow = async (row: PurchaseGood, index: number): Promise<void> => {
  if (!validateEntryRow(row)) return

  try {
    await ElMessageBox.confirm('确认入库商品?', '入库商品', {
      confirmButtonText: t('confirmMessage.ok'),
      cancelButtonText: t('confirmMessage.cancel'),
      type: 'warning'
    })

    const loadingInstance = ElLoading.service({
      text: '正在入库，请稍候',
      background: 'rgba(0, 0, 0, 0.7)',
      fullscreen: true,
      lock: true
    })

    try {
      const params = filterEmptyParams({
        id: row.detail_id,
        entry_num: row.entry_num,
        warehouse: row.warehouse,
        futures: state.futures,
        arrival_batch: row.arrival_batch,
        delivery_date: row.delivery_date,
        ccname_ids: row.ccname_ids
      })

      await entryApi(params)
      await nextTick(() => loadingInstance.close())
      await initialization()
      ElMessage.success('入库成功')
    } catch (error) {
      await nextTick(() => loadingInstance.close())
      throw error
    }
  } catch (error) {
    // 用户取消操作
  }
}

const validateEntryRow = (row: PurchaseGood): boolean => {
  if (!row.warehouse || (Array.isArray(row.warehouse) && row.warehouse.length === 0)) {
    ElMessage.error('请选择仓库')
    return false
  }
  if (!row.ccname_ids || (Array.isArray(row.ccname_ids) && row.ccname_ids.length === 0)) {
    ElMessage.error('请选择可售国家地区')
    return false
  }
  if (!row.entry_num) {
    ElMessage.error('入库数量不能为0')
    return false
  }
  if (!row.arrival_batch || row.arrival_batch.length < 6) {
    ElMessage.error('物流批次不能少于6位')
    return false
  }
  if (state.futures !== FUTURES_TYPES.SPOT && !row.delivery_date) {
    ElMessage.error('到货日期不能为空')
    return false
  }
  return true
}

const getSummaries = (param: SummaryMethodProps) => {
  const needHandleColumns = ['num', 'unit_price', 'unit_sum', 'entered_num', 'entry_num']
  const needShowMoney: string[] = []
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index.toString()] = h('div', { style: { textDecoration: 'underline' } }, ['Total Cost'])
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (
      !values.every((value) => Number.isNaN(value)) &&
      needHandleColumns.includes(column.property)
    ) {
      sums[index] = `${needShowMoney.includes(column.property) ? '¥' : ''} ${values.reduce(
        (prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        },
        0
      )}`
    } else {
      sums[index] = 'N/A'
    }
  })

  return sums
}

// 监听器
watch(
  () => state.row.purchase_goods,
  (newVal, oldVal) => {
    if (!newVal) return

    newVal.forEach((row, index) => {
      const oldRow = oldVal?.[index]
      if (oldRow && !isEqual(row.warehouse, oldRow.warehouse)) {
        getSellableList(2, row.warehouse, row, index)
      }
    })
  },
  { deep: true, immediate: false }
)

// 监听 ccname_ids 的变化
watch(
  () => state.form.ccname_ids,
  (newVal) => {
    if (newVal.includes(0) && newVal.length > 1) {
      // 如果选择了全球且还有其他选项，只保留全球选项
      nextTick(() => {
        state.form.ccname_ids = [0]
      })
    }
  },
  { deep: true }
)

// 监听表格中每个行的 ccname_ids 变化
watch(
  () => state.row.purchase_goods,
  (newVal) => {
    if (!newVal) return

    newVal.forEach((row) => {
      if (row.ccname_ids?.includes(0) && row.ccname_ids.length > 1) {
        nextTick(() => {
          row.ccname_ids = [0]
        })
      }
    })
  },
  { deep: true }
)

// 生命周期钩子
onMounted(initialization)
</script>

<style lang="less" scoped>
:deep(.el-table__cell) {
  text-align: center !important;
}
</style>
